package com.engine.devcom.mode.cmd;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.devcom.mode.entity.BaseRestConfigDto;
import com.engine.devcom.mode.util.BaseRestConfigUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.hrm.User;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : hmy
 * @since : 2025/5/6
 */
public class BaseRestGetDataByConditionCmd extends AbstractCommonCommand<Map<String, Object>> {
    public static Logger LOG = LoggerFactory.getLogger("integration");

    private String interfaceKey;

    public BaseRestGetDataByConditionCmd(String interfaceKey, Map<String, Object> params, User user) {
        this.interfaceKey = interfaceKey;
        this.params = params;
        this.user = user;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        LOG.info("BaseRestGetDataByConditionCmd tag start  " + interfaceKey + " params: " + JSONObject.toJSONString(params));

        BaseRestConfigDto baseRestConfigDto = BaseRestConfigUtils.getBaseRestConfigDto(interfaceKey);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        if (null == baseRestConfigDto) {
            result.put("code", -2);
            result.put("msg", "tag not exists!");
            return result;
        }

        String sql = BaseRestConfigUtils.replaceSqlParams(baseRestConfigDto, params, user);

        LOG.error("BaseRestGetDataByConditionCmd tag: " + interfaceKey + "  sql: " + sql);
        if (StringUtils.isBlank(sql)) {
            result.put("code", -3);
            result.put("msg", "configuration is error!");
            return result;
        }
        RecordSet rs = new RecordSet();
        boolean qryFlag = rs.executeQuery(sql);
        LOG.error("BaseRestGetDataByConditionCmd tag: " + interfaceKey + "  sql: " + sql + "  qryFlag: " + qryFlag + "  msg:" + rs.getMsg());

        if (!qryFlag) {
            result.put("code", -4);
            result.put("errSql", sql);
            result.put("msg", "query error! " + rs.getMsg());
            return result;
        }

        String[] columnNames = rs.getColumnName();
        // 取出查询结果
        Map<String, Object> data = new HashMap<>();
        if (rs.next()) {
            for (String columnName : columnNames) {
                data.put(columnName.toLowerCase(), rs.getString(columnName));
            }
        }
        result.put("code", 0);
        result.put("data", data);
        return result;
    }
}
